import { ITodoItem } from './../../types/data.d';
import { defineStore } from 'pinia'
import request from '../../utils/request'
import footerStore from './footerStore'

const mainStore = defineStore('main', {
  state: () => {
    return {
      list: [] as ITodoItem[]
    }
  },
  actions: {
    /**
     * 获取todos列表
     */
    async getTodos() {
      const { data } = await request.get<ITodoItem[]>('/')
      this.list = data
    },

    /**
     * 删除todos
     * @param id number
     */
    async delTodo(id: number) {
      await request.delete(`/${id}`)
      // 更新todos
      this.getTodos()
    },

    /**
     * 根据id更新状态
     * @param id number
     * @param key string 更新谁
     * @param value string | boolean 更新为什么
     */
    async updateTodo(id: number, key: string, value: boolean | string) {
      await request.patch(`/${id}`, {
        [key]: value
      })
      // 更新todos
      this.getTodos()
    },

    /**
     * 添加todo
     * @param name string
     */
    async addTodo(name: string) {
      await request.post('/', {
        name,
        done: false
      })
      // 更新todos
      this.getTodos()
    },

    /**
     * 更新所有状态
     * @param done 
     */
    async updateAllStatus(done: boolean) {
      const arrPromise = this.list.map(item => {
        return this.updateTodo(item.id, 'done', done)
      })
      await Promise.all(arrPromise)
      // 更新todos
      this.getTodos()
    },

    /**
     * 清空已完成任务
     */
    async clearCompleted() {
      const arrPromise = this.completed.map(item => {
        return this.delTodo(item.id)
      })
      await Promise.all(arrPromise)
      // 更新todos
      this.getTodos()
    }
  },
  getters: {
    // mainRadioStatus(): boolean {
    //   return this.list.every(item => item.done)
    // }
    mainRadioStatus(state){
      return state.list.every(item => item.done)
    },

    // 已完成的任务
    completed(state) {
      return state.list.filter(item => item.done)
    },

    // 未完成的任务
    unCompleted(state) {
      return state.list.filter(item => !item.done)
    },

    
    /**
     * 根据active筛选出来的数据
     */
    renderList(state) {
      const footer = footerStore()
      const { active } = footer
      if (active === 'Active') {
        return state.list.filter(item => !item.done)
      }
      if (active === 'Completed') {
        return state.list.filter(item => item.done)
      }
      return state.list
    }
  }
})

export default mainStore